function imgvol = GetDICOMImage(uid)
%% Get dicom image from either local diectory or from DaRIS. 
%
%  UID string containing DaRIS dataset ID 
%
%   - Michael Eager,  (michael.eager@monash.edu)
%   - (c) 2012  Monash Biomedical Imaging,  Monash University, Australia

%     Copyright © 2012-2013 Michael Eager <michael.eager@monash.edu> 
%
%     This file is part of Xglom.
% 
%     This is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
% 
%     This is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
% 
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/>.

% Check for dataset in Cache
imgvol=[];
currentFolder = pwd;
addpath(fullfile(pwd,'plugins', 'dicom_toolbox_version_2e'));

[status lsoutput] =system(['ls Cache' filesep uid filesep '*.dcm'])

if ~isempty(strfind(lsoutput,'No such file or directory'))
    disp(['Getting dataset ' uid ' from DaRIS.']);

% No explicit checks on whether UID exists on system.  
% Needs further checking of status and lsoutput.
    [status lsoutput] =system(['bash ./dget -c ' uid '  -d Cache ']);

% Check local directory to see if the file was properly downloaded
    [status lsoutput] =system(['ls Cache' filesep uid filesep '*.dcm']);
    lsoutput = regexprep(lsoutput,'\n','');
    if status ~= 0
        display 'Error in Downloading dataset.'
        return
    end

    if size(lsoutput,1) == 1
        display 'Downloading dataset complete. Reading in.'
        imgvol = dicom_read_volume(lsoutput);
% hack to remove dicom_read_volume dialog
        hReadInDialog=get(0,'CurrentFigure');close(hReadInDialog);
        display 'DICOM loaded.'
        %char(['./Cache' filesep uid filesep '0001.dcm']));
        
    else
        display 'Too many dcm files in dataset directory.'
    end
else
% Dicom is in local directory
    display 'Dataset in Cache. Loading in.'
    lsoutput = regexprep(lsoutput,'\n','')
    imgvol = dicom_read_volume(lsoutput);
% hack to remove dicom_read_volume dialog
    hReadInDialog=get(0,'CurrentFigure');close(hReadInDialog); 
    display ' DICOM loaded.'
    
end
imgvol = single(imgvol);
imgvol = squeeze(imgvol);
disp(['GetImage retreived image mean : ' num2str(mean(imgvol(:)))])

        
